package com.farecrawler.app.job;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import org.apache.commons.mail.EmailException;
import org.apache.log4j.Logger;

import com.farecrawler.app.airlines.TigerUtils;
import com.farecrawler.app.email.Formatter;
import com.farecrawler.app.exception.FareCrawlException;
import com.farecrawler.app.model.FlightInfo;
import com.farecrawler.app.model.FlightRequest;
import com.farecrawler.app.net.TigerConnection;
import com.farecrawler.app.utils.DateUtils;
import com.farecrawler.app.utils.EmailUtils;

public class TigerAirJob {
	
	private Logger log = Logger.getLogger(TigerAirJob.class);
	private TigerConnection tigerConnection;
	private Formatter emailFormatter;
	
	public void startJob(List<Calendar> departDateList, String origin, String destination) throws FareCrawlException {
		
		List<FlightInfo> result = new ArrayList<FlightInfo>();
		
		for(Calendar departDate : departDateList){
			
			Calendar returnDate = createReturnDateHelper(departDate);
			
			List<FlightInfo> departureList = retrieveFlightInfo(origin, destination, departDate, returnDate);
			result.addAll(departureList);
		}
		
		sendEmail(result);
	}

	private List<FlightInfo> retrieveFlightInfo(String origin, String destination, 
			Calendar departDate, Calendar returnDate) throws FareCrawlException {
		
		FlightRequest flightRequest = new FlightRequest(departDate, returnDate, origin, destination);
		tigerConnection.connect(flightRequest);
		return tigerConnection.getDepartureList();
	}

	private Calendar createReturnDateHelper(Calendar departDate) {
		
		Date date = DateUtils.add(departDate.getTime(), Calendar.DATE, +3);
		Calendar returnDate = Calendar.getInstance();
		returnDate.setTime(date);
		return returnDate;
	}
	
	private void sendEmail(List<FlightInfo> flightList) throws FareCrawlException{
		
		log.info("Formatting email.");
		emailFormatter.formatHtmlEmail(flightList);
		String emailBody = emailFormatter.getEmailBody();

		log.info("Sending email.");
		try {
			EmailUtils.sendHtmlEmail(TigerUtils.EMAIL_SUBJECT, emailBody);
			log.info("Email sent.");
			
		} catch (EmailException e) {
			throw new FareCrawlException(e.getMessage());
		} 
	}

	/*
	 * Getters Setters
	 */
	public TigerConnection getTigerConnection() {
		return tigerConnection;
	}

	public void setTigerConnection(TigerConnection tigerConnection) {
		this.tigerConnection = tigerConnection;
	}

	public Formatter getEmailFormatter() {
		return emailFormatter;
	}

	public void setEmailFormatter(Formatter emailFormatter) {
		this.emailFormatter = emailFormatter;
	}
	
	

}
